package win.zxshuo.www.TextUtils;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.mozilla.universalchardet.UniversalDetector;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Reader {

    private Log logger = LogFactory.getLog(getClass());

    /**
     * 章节的正则表达式
     */
    private String pattern = "^.*第[一二三四五六七八九十0123456789]+章.*";

    private String toBeRemovePattern = "色中色·TXT文学打包区";


    public String getFileEncoding(String filePath){
        String encoding="UTF-8";
        try{
            File file = new File(filePath);
            InputStream is = new FileInputStream(file);
            UniversalDetector detector = new UniversalDetector(null);
            try {
                byte[] bytes = new byte[1024];
                int nread;
                if ((nread = is.read(bytes))>0 && !detector.isDone()){
                    detector.handleData(bytes,0,nread);
                }
            }catch (Exception e){
                logger.error(e.getCause());
            }
            detector.dataEnd();
            encoding = detector.getDetectedCharset();
            detector.reset();
        }catch (Exception e){
            logger.error(e.getCause());
        }
        return encoding;
    }

    /**
     * 逐行读取文本
     * @param filePath
     * @return
     */
    public List<String> ReadTextLineByLine(String filePath){
        List<String> lines = new ArrayList<>();
        File file = new File(filePath);
        if (file.exists() & file != null){
            try {
                String charset = getFileEncoding(filePath);
                InputStreamReader reader = new InputStreamReader(new FileInputStream(file),charset);
                BufferedReader bufferedReader = new BufferedReader(reader);
                String lineText = "";
                while (lineText != null){
                    lineText = bufferedReader.readLine();
                    if (lineText !=null ){
                        lines.add(lineText);
                    }
                }
            }catch (Exception e){
                logger.error(e.getCause());
            }
        }
        return lines;
    }


    /**
     * 将逐行读取的列表分段
     * 这里因为utf8编码是带bom的因此匹配正则出错了，坑了我一晚上，因此需要替换掉bom部分\ufeff
     * @param lines
     * @return
     */
    public List<Chapter> parseLinesToParagraph(List<String> lines){
        List<Chapter> paragraphs = new ArrayList<>();
        String p = "";
        Chapter chapter = new Chapter();
        for (String line:lines){
            System.out.println("line = [" + line + "]");
            String noSpaceStr = line.replace("　","").replace("\ufeff","");
            Boolean status = Pattern.matches(pattern,noSpaceStr);
            Boolean status2 = Pattern.matches(pattern,line);
            if (status || status2){
                p = "";
                System.out.println("符合条件");
                if (chapter.getTitle() == null && chapter.getParagraphs() ==null){
                    System.out.println("都为空，添加了标题后结束这次循环");
                    chapter.setTitle(noSpaceStr);
                    continue;
                }
                chapter.addParagraph(p);
                paragraphs.add(chapter);
                chapter = new Chapter();
                chapter.setTitle(noSpaceStr);
                continue;
            }
            Pattern pt = Pattern.compile(toBeRemovePattern);
            Matcher matcher = pt.matcher(p);
            if (matcher.find()){
                line = matcher.replaceAll("");
            }
            if (line.contains("　")){

                chapter.addParagraph(p);
                p = line;
            }else {
                p = p + line;
            }
        }
        chapter.addParagraph(p);
        paragraphs.add(chapter);
//        if (paragraphs.size()<=0){
//            for (String line:lines){
//                Chapter chapter = new Chapter();
//                chapter.set
//            }
//            return lines;
//        }
        return paragraphs;
    }




}
